package com.mdd.common.plugin.sms.engine;

import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;

import java.util.Map;
import java.util.Properties;

public class EmailSms {
    private final Map<String, String> config; // 短信配置
    private Integer sendResult;     // 发送结果
    private String mobile;          // 手机号码
    private String subject;
    private String content;

    /**
     * 构造方法
     *
     * @param config 短信配置
     * @author fzr
     */
    public EmailSms(Map<String, String> config) {
        this.config = config;
    }

    /**
     * 设置手机号
     *
     * @param mobile 手机号码
     * @return AliSms
     * @author fzr
     */
    public EmailSms setMobile(String mobile) {
        this.mobile = mobile;
        return this;
    }


    public EmailSms setContent(String content) {
        this.content = content;
        return this;
    }

    public EmailSms setSubject(String subject) {
        this.subject = subject;
        return this;
    }

    /**
     * 获取发送结果
     *
     * @return Integer [1=成功, 2=失败]
     * @author fzr
     */
    public Integer getSendResult() {
        return this.sendResult;
    }

    /**
     * 发送短信
     *
     * @return String
     * @author fzr
     */
    public String send() {
        JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
        mailSender.setHost(this.config.get("host"));
//        mailSender.setProtocol(this.config.get("protocol"));
        mailSender.setPort(Integer.parseInt(this.config.get("port")));
        mailSender.setUsername(this.config.get("user_name"));
        mailSender.setPassword(this.config.get("pass_word"));
        Properties props = mailSender.getJavaMailProperties();
        // 开启 SMTP 认证
        props.put("mail.smtp.auth", "true");
        // 开启 ssl 加密
        props.put("mail.smtp.ssl.enable", "true");
        try {
            SimpleMailMessage message = new SimpleMailMessage();
            message.setFrom(this.config.get("user_name"));
            message.setTo(this.mobile);
            message.setSubject(subject);
            message.setText(content);
            mailSender.send(message);
            this.sendResult = 1;
            return "发送成功！";
        } catch (Exception e) {
            this.sendResult = 2;
            return e.getMessage();
        }
    }
}
